package com.db.concurrency.producerconsumer.threads;

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CountDownLatch;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class FileCrawler implements Runnable {
    private final BlockingDeque<File> fileQueue;
    private final FileFilter fileFilter;
    private final File root;
    private final CountDownLatch doneSignal;

    public FileCrawler(List<BlockingDeque<File>> tasksList,
                       int id,
                       final FileFilter fileFilter,
                       File root,
                       CountDownLatch doneSignal) {
        this.fileQueue = tasksList.get(id);
        this.root = root;
        this.fileFilter = new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || fileFilter.accept(f);
            }
        };
        this.doneSignal = doneSignal;
    }

    private boolean alreadyIndexed(File f) {
        return false;
    }

    public void run() {
        try {
            crawl(root);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            doneSignal.countDown();
        }
    }

    private void crawl(File root) throws InterruptedException {
        File[] entries = root.listFiles(fileFilter);
        if (entries != null) {
            for (File entry : entries) {
                if (entry.isDirectory()) {
                    crawl(entry);
                } else if (!alreadyIndexed(entry)) {
                    fileQueue.put(entry);
                }
            }
        }
    }
}

